import React, { PureComponent } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import OrganTreeList from '@/components/AsyncLoadingTreeList';
import {
	Table,
	Card,
	Form,
	message,
} from 'antd';

const FormItem = Form.Item;
import styles from './ProUserOrganList.less';

import CreateForm from './ProUserOrganCreateForm';//新增表单
import UpdateForm from './ProUserOrganUpdateForm';//修改表单
import ViewForm from './ProUserOrganViewForm';//查看表单


function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
   return totalList;
}
class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);
    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };
  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'id' || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
        />
      </div>
    );
  }
}


@connect(({ prouserorgan, loading }) => ({
    prouserorgan,
    loading: loading.models.prouserorgan,
}))
@Form.create()
class ProUserOrganList extends PureComponent {
	state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        addOrganTreeInfo:{},
        root_parentid:'000000000000',
        reLoadOrganTree: "",
        reloadOrganTreeUpdate: "",
        reloadOrganTreeDelete: "",
        orgCode:"",
        
    };

    columns = [

        {
	        title: '用户名',
	        dataIndex: 'user_name',
        }, 
        {
	        title: '用户名称',
	        dataIndex: 'user_name_cn',
        },        
        {
	        title: '用户密码',
	        dataIndex: 'password',
        },
        {
	        title: '手机号码',
	        dataIndex: 'phone',
        },
        {
	        title: '机构代码',
	        dataIndex: 'org_code',
        },
        
	];
    constructor(props) {
     	super(props);
    }

   componentDidMount() {
		const { dispatch } = this.props;
	    dispatch({
	        type: 'prouserorgan/get_page_proorg_by_orgcode',
	    });
    }

  componentWillUnmount() {

  }
handleModalVisible = (flag,record,reLoadCurrentTreeNode) => {
    this.setState({
        modalVisible: !!flag,
        addOrganTreeInfo: record || {},
        reLoadOrganTree: reLoadCurrentTreeNode,
    });
};

reLoadOrganTreeNodeDelete = (flag) => {
	this.setState({
		reloadOrganTreeDelete: flag
    });
}

handleAdd = async (addOrganTreeInfo,fields) => {
    const { dispatch } = this.props;
    const { key,levelcode } = addOrganTreeInfo.props.dataRef;
    await dispatch({
        type: 'prouserorgan/insert_for_proorg',
        payload: {
        	root_parentid:this.state.root_parentid,
            org_name: fields.title,
            org_code: fields.org_code,
            parentid: key,
            levelcode: levelcode,
        }
    });
    const { prouserorgan:{ recorddata } } = this.props;
	this.state.reLoadOrganTree(recorddata.datarecord,addOrganTreeInfo.props.eventKey);
    this.handleModalVisible();
    message.success('添加成功');
};

handleUpdateModalVisible = (flag, record,reLoadCurrentTreeNodeUpdate) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
        reloadOrganTreeUpdate: reLoadCurrentTreeNodeUpdate,       
    });
};

handleUpdate = async ( organTreeRecord,fields ) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    await dispatch({
        type: 'prouserorgan/update_for_proorg',
        payload: {
        	  root_parentid:this.state.root_parentid,
	          org_id: fields.org_id,
	          org_name: fields.title,
	          org_code: fields.org_code,
	          parentid: fields.parentid,
	          levelcode: fields.levelcode
        },
    });
	this.state.reloadOrganTreeUpdate(fields,organTreeRecord.props.eventKey,organTreeRecord.props.dataRef.parentid);
    this.handleUpdateModalVisible();
 	message.success('修改成功');

};

handleDeleteRecord = (record,reLoadCurrentTreeNodeDelete) => {
    const { dispatch } = this.props;
    dispatch({
        type: 'prouserorgan/delete_by_primarykey_for_proorg',
        payload: {
        	root_parentid:this.state.root_parentid,
        	recordid: record.props.dataRef.org_id,
        },
        callback: () => {
	        this.setState({
	        	selectedRows: [],
	        });
	        reLoadCurrentTreeNodeDelete(record.props.eventKey);
        },
    });
    message.success('删除成功');
};


handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
        expandForm: !expandForm,
    });
};
handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
    });
    dispatch({
        type: 'prouserorgan/query_page_for_userorgan',
        payload: {},
    });
};

handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

    const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
    };

    this.setState({
        formValues: values,
    });

    dispatch({
        type: 'prouserorgan/query_page_for_prouserorgan',
        payload: values,
    });
});
};

handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,orgCode } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
        const newObj = { ...obj };
	    newObj[key] = getValue(filtersArg[key]);
	    return newObj;
	}, {});

    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
        org_code: orgCode,
    };
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'prouserorgan/get_page_proorg_by_orgcode',
        payload: params,
    });
};

checkedTreeChild = node => {
	const orgCode = node.props.dataRef.org_code;
	const { dispatch } = this.props;
  	dispatch({
        type: 'prouserorgan/get_page_proorg_by_orgcode',
        payload: {
        	org_code: orgCode,
        }
  	});
  	this.setState({
  		orgCode: orgCode,
  	})
};

handleSelectRows = rows => {
  	this.setState({
        selectedRows: rows,
   });
};

  render() {
  	const {
        prouserorgan: { data,organTree },
        loading,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, viewModalVisible,  updateFormValues,  viewFormValues,addOrganTreeInfo } = this.state;
    const parentMethods = {
        handleAdd: this.handleAdd,
        handleModalVisible: this.handleModalVisible,
        addOrganTreeInfo: addOrganTreeInfo
    };
    const parentRole = {
   		dispatch: this.props.dispatch,
   		checkedTreeChild: this.checkedTreeChild,
   	  handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
     	handleDeleteRecord: this.handleDeleteRecord,
     	handleViewModalVisible: this.handleViewModalVisible,
     	rootNodeName:"机构",
	    searchTreePlaceholder:"请选择机构",
	    asyncLoadingTreeUrl:'prouserorgan/get_proorgtree_by_parentid',
	    updateTreeNodeBydragUrl:'prouserorgan/update_change_target_node_with_source_node_pro_org',
    }
    const updateMethods = {
        handleUpdateModalVisible: this.handleUpdateModalVisible,
        handleUpdate: this.handleUpdate,
    };
    const viewMethods = {
        handleViewModalVisible: this.handleViewModalVisible
    };
    return (
            <PageHeaderWrapper title="机构用户信息列表">
            <Card bordered={false}>
            <div className={styles.proMenutableList}>
            <div className={styles.proMenutableListOperator}>
    </div>
        <OrganTreeList {...parentRole} treeList={organTree}/>

        <StandardTable
        rowKey={'user_id'}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
        {updateFormValues && Object.keys(updateFormValues).length ? (
            <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}
        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}
    </PageHeaderWrapper>
    );
  }
}

export default ProUserOrganList;